package shuran;

import com.server.protobuf.ImModel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    public ChannelHandlerContext context;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            IdleState state = event.state();

            if (state.equals(IdleState.READER_IDLE)) {
                System.out.println("客户端读空闲" + IdleState.READER_IDLE);
            }
            if (state.equals(IdleState.WRITER_IDLE)) {
                System.out.println("客户端写空闲" + IdleState.WRITER_IDLE);
            }
            if (state.equals(IdleState.ALL_IDLE)) {
                System.out.println("客户端读写空闲" + IdleState.ALL_IDLE);
            }
            Thread.sleep(3000);
            ctx.writeAndFlush(createMessage(ImModel.Type.PING, "PING"));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ImModel.Command) {
            ImModel.Command command = (ImModel.Command) msg;
            if (ImModel.Type.PONG.equals(command.getType())) {
                System.out.println("接收到服务器器端PONG" + command.getContent());
            }
        }
    }

    // 连接成功后，向server发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
        System.out.println("连接成功，向服务器发送消息");
        ctx.writeAndFlush(createMessage(ImModel.Type.PRIVATE, "command Message"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务器端强制关闭连接:" + ctx.channel().remoteAddress());
    }

    private ImModel.Command createMessage(ImModel.Type type, String content) {
        ImModel.Command.Builder command = ImModel.Command.newBuilder();
        command.setId(13853);
        command.setCid("test");
        command.setType(type);
        command.setContent(content);
        return command.build();
    }
}
